package com.boilermaker.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 对 Spring 集成的 Redis 服务进一步封装，以统一处理异常
 */
@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private StringRedisTemplate srt;

    public boolean set(String key, String val) {
        try {
            srt.opsForValue().set(key, val);
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error, set({}, {})", key, val, e);
            return false;
        }
    }

    /**
     * 带有过期时间的 set 方法
     *
     * @param key
     * @param val
     * @param ttl 单位：s
     * @return
     */
    public boolean set(String key, String val, Long ttl) {
        try {
            srt.opsForValue().set(key, val, ttl, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error, set({},{}), ttl:{}", key, val, ttl, e);
            return false;
        }
    }

    public String get(String key) {

        if (!StringUtils.hasText(key)) {
            return null;
        }

        try {
            return srt.opsForValue().get(key);
        } catch (Exception e) {
            log.error("RedisUtil error, get({})", key, e);
            return null;
        }
    }

    public boolean delete(String... key) {
        try {
            if (key != null && key.length > 0) {
                srt.delete(List.of(key));
            }
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error, del({})", key, e);
            return false;
        }
    }

    public boolean hasKey(String key) {
        if (!StringUtils.hasText(key)) {
            return false;
        }

        try {
            return srt.hasKey(key);
        } catch (Exception e) {
            log.error("RedisUtil error, hasKey({})", key, e);
            return false;
        }
    }
}

